import { Address, Button, Checkbox, Form, Input } from '@nutui/nutui-react-taro'
import { Text, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useEffect, useState } from 'react'
import Layout from '../../components/layout'
import './index.less'

const EditAddress = () => {
  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    region: '', // 省市区
    address: '', // 详细地址
    isDefault: false,
  })
  const [isEdit, setIsEdit] = useState(false)
  const [showAddress, setShowAddress] = useState(false)
  const [regionCode, setRegionCode] = useState<string[]>([])

  const options = [
    {
      value: '浙江',
      text: '浙江',
      children: [
        {
          value: '杭州',
          text: '杭州',
          disabled: true,
          children: [
            { value: '西湖区', text: '西湖区', disabled: true },
            { value: '余杭区', text: '余杭区' },
          ],
        },
        {
          value: '温州',
          text: '温州',
          children: [
            { value: '鹿城区', text: '鹿城区' },
            { value: '瓯海区', text: '瓯海区' },
          ],
        },
      ],
    },
    {
      value: '湖南',
      text: '湖南',
      disabled: true,
      children: [
        {
          value: '长沙',
          text: '长沙',
          disabled: true,
          children: [
            { value: '西湖区', text: '西湖区' },
            { value: '余杭区', text: '余杭区' },
          ],
        },
        {
          value: '温州',
          text: '温州',
          children: [
            { value: '鹿城区', text: '鹿城区' },
            { value: '瓯海区', text: '瓯海区' },
          ],
        },
      ],
    },
    {
      value: '福建',
      text: '福建',
      children: [
        {
          value: '福州',
          text: '福州',
          children: [
            { value: '鼓楼区', text: '鼓楼区' },
            { value: '台江区', text: '台江区' },
          ],
        },
      ],
    },
  ]

  useEffect(() => {
    const router = Taro.getCurrentInstance().router
    const { id } = router?.params || {}

    if (id) {
      setIsEdit(true)
      // 这里应该根据 id 获取地址详情
      // 暂时使用模拟数据
      setFormData({
        name: '张三',
        phone: '138****8888',
        region: '江苏省南京市江宁区',
        address: '东山街道文靖东路168号3单元101室',
        isDefault: false,
      })
      setRegionCode(['320000', '320100', '320115']) // 江苏省南京市江宁区的编码
    }
  }, [])

  const handleInputChange = (field: string, value: string | boolean) => {
    setFormData((prev) => ({
      ...prev,
      [field]: value,
    }))
  }

  // 处理省市区选择
  const handleRegionChange = (values: string[], options: any[]) => {
    setRegionCode(values)
    const regionText = options.map((item) => item.text).join('')
    setFormData((prev) => ({
      ...prev,
      region: regionText,
    }))
  }

  // 打开省市区选择器
  const openAddressSelector = () => {
    setShowAddress(true)
  }

  // 关闭省市区选择器
  const closeAddressSelector = () => {
    setShowAddress(false)
  }

  const handleSubmit = (values: any) => {
    // 这里应该调用 API 保存地址
    console.log('保存地址:', values)

    Taro.showToast({
      title: isEdit ? '地址更新成功' : '地址添加成功',
      icon: 'success',
    })

    // 延迟返回上一页
    setTimeout(() => {
      Taro.navigateBack()
    }, 1500)
  }

  const handleSubmitFailed = (error: any) => {
    console.log('表单验证失败:', error)
  }

  return (
    <Layout title={isEdit ? '编辑地址' : '添加地址'} showTabBar={false}>
      <View className='edit-address'>
        <Form
          initialValues={formData}
          onFinish={handleSubmit}
          onFinishFailed={handleSubmitFailed}
          className='address-form'>
          <View className='form-section'>
            <Form.Item
              label='收货人'
              name='name'
              rules={[
                { required: true, message: '请输入收货人姓名' },
                { min: 2, message: '姓名至少2个字符' },
              ]}>
              <Input
                placeholder='请输入收货人姓名'
                value={formData.name}
                onChange={(value) => handleInputChange('name', value)}
              />
            </Form.Item>

            <Form.Item
              label='手机号'
              name='phone'
              rules={[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
              ]}>
              <Input
                placeholder='请输入手机号'
                value={formData.phone}
                onChange={(value) => handleInputChange('phone', value)}
                type='number'
                maxLength={11}
              />
            </Form.Item>
          </View>

          <View className='form-section'>
            <Form.Item label='省市区' name='region' rules={[{ required: true, message: '请选择省市区' }]}>
              <View className='region-selector' onClick={openAddressSelector}>
                <Input placeholder='请选择省市区' value={formData.region} readOnly />
              </View>
            </Form.Item>

            <Form.Item
              label='详细地址'
              name='address'
              rules={[
                { required: true, message: '请输入详细地址' },
                { min: 5, message: '详细地址至少5个字符' },
              ]}>
              <Input
                placeholder='请输入街道、门牌号等详细地址'
                value={formData.address}
                onChange={(value) => handleInputChange('address', value)}
                type='textarea'
              />
            </Form.Item>

            <Form.Item name='isDefault' valuePropName='checked'>
              <View className='checkbox-item'>
                <Checkbox
                  checked={formData.isDefault}
                  onChange={(checked) => handleInputChange('isDefault', checked)}
                />
                <Text className='checkbox-label'>设为默认地址</Text>
              </View>
            </Form.Item>
          </View>

          <View className='submit-section'>
            <Button type='primary' size='large' block formType='submit'>
              {isEdit ? '更新地址' : '添加地址'}
            </Button>
          </View>
        </Form>

        {/* 省市区选择器弹窗 */}

        <Address
          value={regionCode}
          options={options}
          visible={showAddress}
          onClose={closeAddressSelector}
          onChange={handleRegionChange}
        />
      </View>
    </Layout>
  )
}

export default EditAddress
